/**
 * 
 */
package com.alkandros.linesmash.ui;

import hu.accedo.commons.widgets.AsyncImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.alkandros.linesmash.R;
import com.alkandros.linesmash.adapter.ExpandableRestaurantAdapter;
import com.alkandros.linesmash.adapter.RestaurantAdapter;
import com.alkandros.linesmash.location.ILocationCallBack;
import com.alkandros.linesmash.manager.APIManager;
import com.alkandros.linesmash.manager.AlertManager;
import com.alkandros.linesmash.models.Restaurant;
import com.alkandros.linesmash.models.RestaurantMenuItem;
import com.alkandros.linesmash.models.RestaurantMenuModel;

/**
 * @author Jiju Induchoodan
 *
 */
public class RestaurantMenu extends BaseActivity implements ILocationCallBack {
	
	ExpandableRestaurantAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<Restaurant>> listDataChild;
    private Restaurant restaurant;
    private Restaurant restaurantModelReceived;
    ArrayList<Restaurant> resItemArray;
    
    private TextView textResName;
    private RatingBar ratingRestaurant;
    AsyncImageView imageView;
    private TextView txtBottomRight;
    private Intent intent;
    FetchRestaturantMenu fetchRestaurantMenu;
    HashMap<String, List<RestaurantMenuItem>> restaurantMap;
    private ArrayList<RestaurantMenuItem> menuItemArray;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.restaurant_menu);
        Bundle extras=getIntent().getExtras();
        if(extras!=null)
        {
        	restaurantModelReceived = (Restaurant)extras.getSerializable("model");
        }
        setHeading(restaurantModelReceived.getTitle());
	    setLeftButton();
	    setRightButton();
	    setCartButton();
        expListView 			= (ExpandableListView) findViewById(R.id.list);
        imageView				= (AsyncImageView)findViewById(R.id.img_item);
        txtBottomRight			= (TextView)findViewById(R.id.right_button);
        textResName				= (TextView)findViewById(R.id.location);
        ratingRestaurant		= (RatingBar)findViewById(R.id.rating);
        
        
        txtBottomRight.setText(R.string.checkout);
        imageView.setUrl(restaurantModelReceived.getImage());
        ratingRestaurant.setRating(restaurantModelReceived.getRating());
        textResName.setText(restaurantModelReceived.getTitle());
        
        
        fetchRestaurantMenu = new FetchRestaturantMenu();
        fetchRestaurantMenu.execute();
        
     //   prepareListData();
      
        expListView.setGroupIndicator(null);
        expListView.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
					int arg3, long arg4) {
				intent = new Intent(RestaurantMenu.this,OrderMenuSelection.class);
				intent.putExtra("model", restaurantModelReceived);
				intent.putExtra("restuarant_item", restaurantMap.get(listDataHeader.get(arg2)).get(arg3));
				Log.e("", "Child clicked"+restaurantMap.get(listDataHeader.get(arg2)).get(arg3).getPrice());
				
				
				startActivity(intent);
				return false;
			}
		});
    }
 
   
    class FetchRestaturantMenu extends AsyncTask<Void, Void, Void>
	{
		private APIManager manager;
		private boolean isException=false;
		private String response;
		private String [] names= {"",""};
		private String [] values= {"",""};
		
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			progress.dismiss();
			if(isException)
			{
				AlertManager.shorttoastMessage(RestaurantMenu.this, getString(R.string.common_error_message));
			}
			else
			{
				if(response.contains(ERROR_CODE))
				{
					AlertManager.shorttoastMessage(RestaurantMenu.this, getString(R.string.common_error_message));
				}
				else
				{
					try
					{
						JSONObject obj = new JSONObject(response);
						JSONArray array = obj.getJSONArray(DATA);
						listDataHeader = new ArrayList<String>();
						menuItemArray = new ArrayList<RestaurantMenuItem>();
						restaurantMap  = new HashMap<String, List<RestaurantMenuItem>>();
						//listDataChild 	= new HashMap<String, List<Restaurant>>();
						for (int i = 0; i < array.length(); i++) 
						{
							RestaurantMenuModel model = new RestaurantMenuModel();
							JSONObject postObject = array.getJSONObject(i).getJSONObject(RESTAURANT_MENU);
							model.setTitle(postObject.getString(TITLE));
							listDataHeader.add(model.getTitle());
							
							JSONArray menuArray = array.getJSONObject(i).getJSONArray(MENU_ITEM);
							Log.d("", "Menu array"+menuArray.length());
							menuItemArray = new ArrayList<RestaurantMenuItem>();
							for (int j = 0; j < menuArray.length(); j++) {
								
								RestaurantMenuItem item = new RestaurantMenuItem();
								JSONObject menuObject = menuArray.getJSONObject(j);
								item.setName(menuObject.getString(TITLE));
								item.setPrice(menuObject.getString(PRICE));
								
								menuItemArray.add(item);
								restaurantMap.put(listDataHeader.get(i), menuItemArray);
								
								
							}
							Log.e("", "Menu item array"+menuItemArray.size());
							Log.e("", "Restaurant Map"+restaurantMap.size());
					//		restaurantArray.add(model);
						}
						
						Log.e("", "Restaurant Map"+restaurantMap.keySet());
					//		resAdapter = new RestaurantAdapter(context,restaurantArray);
					//		list.setAdapter(resAdapter); 
					}
					catch(Exception e)
					{
						Log.e("", "Exception"+e.getMessage());
						AlertManager.shorttoastMessage(RestaurantMenu.this, getString(R.string.common_error_message));
					}
					
					  listAdapter = new ExpandableRestaurantAdapter(RestaurantMenu.this, listDataHeader, restaurantMap);
				      expListView.setAdapter(listAdapter);
					
				}
			}
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress.show();
			manager = new APIManager(URL_RESTAURANT_MENU);
		}

		@Override
		protected Void doInBackground(Void... params) {
			try 
			{
				response= manager.commonPostData(URL_RESTAURANT_MENU+restaurantModelReceived.getId(),names,values);
			}
			catch (Exception e)
			{
				e.printStackTrace();
				isException=true;
			}
			return null;
		}
		
	}

	/* (non-Javadoc)
	 * @see com.alkandros.linesmash.location.ILocationCallBack#setResult(java.lang.String)
	 */
	@Override
	public void setResult(String address) {
		// TODO Auto-generated method stub
		
	}
}